package com.sms.model;

import com.sms.exception.DataFileCorruptedException;
import com.sms.util.FileUtil;
import com.sms.util.ValidateUtil;

import java.io.IOException;
import java.util.List;

import static com.sms.constants.SystemConstants.STUDENT_FILE;

/**
 * 学生实体类
 * 位置：com.sms.model.Student
 */
public class Student {
    // 属性定义
    private String id;        // 学号，主键，7位数字
    private String name;      // 姓名，2-10字符
    private int age;          // 年龄，15-50
    private String gender;    // 性别，M/F
    private String className; // 班级名称

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }


    /**
     * 验证学生数据有效性
     *
     * @return true-数据有效, false-数据无效
     */
    public boolean isValid() {
        return ValidateUtil.isValidStudentId(this.id)
                && ValidateUtil.isValidName(this.name)
                && ValidateUtil.isValidAge(this.age)
                && ValidateUtil.isValidGender(this.gender)
                && this.className != null && !this.className.trim().isEmpty();
    }

    /**
     * 转换为文件存储格式
     *
     * @return CSV格式字符串："id,name,age,gender,className"
     */
    public String toFileString() {
        return (this.id + "," +
                this.age + "," +
                this.gender + "," +
                this.className + "," +
                System.lineSeparator());
    }

    /**
     * 从文件行解析学生对象
     *
     * @param line 文件行内容（CSV格式）
     * @return 解析后的Student对象
     * @throws IOException                当文件读取失败时抛出
     * @throws DataFileCorruptedException 当数据格式错误时抛出
     */
    public static Student fromFileString(String line) throws DataFileCorruptedException, IOException {
        List<Student> students = FileUtil.loadStudents(STUDENT_FILE);
        return students.get(Integer.parseInt(line) - 1);
    }
}